﻿// -----------------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All rights reserved.
// -----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition.AttributedModel;
using System.ComponentModel.Composition.ReflectionModel;
using System.Reflection;
using Microsoft.Internal;

namespace System.ComponentModel.Composition.Caching.AttributedModel
{
    internal class CachedAttributedExportDefinition : ExportDefinition
    {
        public CachedAttributedExportDefinition(IDictionary<string, object> cache)
        {
            Assumes.NotNull(cache);

            this.Cache = cache;
        }

        public IDictionary<string, object> Cache
        {
            get;
            private set;
        }

        public override string ContractName
        {
            get { return this.Cache.ReadValue<string>(AttributedCacheServices.CacheKeys.ContractName); }
        }

        public override IDictionary<string, object> Metadata
        {
            get { return this.Cache.ReadDictionary<object>(AttributedCacheServices.CacheKeys.Metadata); }
        }

        public static IDictionary<string, object> CreateCache(AttributedMemberExportDefinition export)
        {
            Assumes.NotNull(export);

            IDictionary<string, object> cache = new Dictionary<string, object>();
            cache.WriteValue(AttributedCacheServices.CacheKeys.ContractName, export.ContractName);
            cache.WriteDictionary(AttributedCacheServices.CacheKeys.Metadata, export.Metadata);
            cache.WriteMember(export.Member);

            return cache;
        }

        internal MemberInfo GetMember()
        {
            return this.Cache.LoadMember();
        }

        public ExportingMember ToExportingMember()
        {
            MemberInfo member = GetMember();

            return new ExportingMember(this, member.ToReflectionMember());
        }
    }
}
